﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplicationTest
{
    /// <summary>
    /// 从网页参数调用打包示例
    /// http://localhost:5516/ApkTool.aspx?GAMEID=1001&CHANNELID=0000001&APK=D:\sci\网游打包工具2\APK_Base\游戏裸包\1001\v2.0.1\ltsdk_Demo_1.apk&SIGN=letang&OUTDIR=C:\Users\wangzhongyuan\Desktop\test\out&ICONDIR=C:\Users\wangzhongyuan\Desktop\test\Icon
    /// http://10.80.1.178/ApkTool.aspx?GAMEID=1001&CHANNELID=0000001&APK=D:\sci\网游打包工具2\APK_Base\游戏裸包\1001\v2.0.1\ltsdk_Demo_1.apk&SIGN=letang&ICONDIR=C:\Users\wangzhongyuan\Desktop\test\Icon
    /// </summary>
    public partial class ApkTool : System.Web.UI.Page
    {
        String GAMEID = "";
        String CHANNELID = "";
        String APK = "";
        String SIGN = "";
        String OUTDIR = "";
        String ICONDIR = "";

        String ToolDir = "";
        String DownloadPage = "";

        /// <summary>
        /// 载入打包参数信息
        /// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = Request.Url.ToString();

            GAMEID = Request.Params.Get("GAMEID");
            CHANNELID = Request.Params.Get("CHANNELID");
            APK = Request.Params.Get("APK");
            SIGN = Request.Params.Get("SIGN");
            OUTDIR = Request.Params.Get("OUTDIR");
            ICONDIR = Request.Params.Get("ICONDIR");

            ToolDir = HttpContext.Current.Server.MapPath("tools/");
            DownloadPage = Request.Params.Get("HTTP_HOST") + "/Download.aspx";

            if (OUTDIR == null || OUTDIR.Equals("")) OUTDIR = HttpContext.Current.Server.MapPath("Uploads/");

            // 调用打包工具打包
            if (GAMEID != null && CHANNELID != null && APK != null && !GAMEID.Equals("") && !CHANNELID.Equals("") && !APK.Equals(""))
            {
                process(GAMEID, CHANNELID, APK, SIGN, OUTDIR, ICONDIR);

                //Response.Redirect(DownloadPage, false);
            }
            //Cmd.ThreadRun(process);
        }

        //public void process()
        //{
        //    // 调用打包工具打包
        //    if (GAMEID != null && CHANNELID != null && APK != null && !GAMEID.Equals("") && !CHANNELID.Equals("") && !APK.Equals(""))
        //    {
        //        process(GAMEID, CHANNELID, APK, SIGN, OUTDIR, ICONDIR);

        //        Response.Redirect(DownloadPage, false);
        //    }
        //}

        /// <summary>
        /// 调用打包工具打包
        /// </summary>
        private void process(String GAMEID, String CHANNELID, String APK, String SIGN = "", String OUTDIR = "", String ICONDIR = "")
        {
            //string dirPath = HttpContext.Current.Server.MapPath("tools/");
            string dirPath = ToolDir;
            if(!Directory.Exists(dirPath)) dirPath = @"D:\sci\Visual Studio 2008\Projects\APK_Tool\APK_Tool\bin\Debug\";
            String APKTOOL = AddQuotation(dirPath + "APK_Tool.exe");
            

            String arg = AddQuotation("GAMEID=" + GAMEID) + " " + AddQuotation("CHANNELID=" + CHANNELID) + " " + AddQuotation("APK=" + APK);
            if (SIGN != null && !SIGN.Equals("")) arg += " " + AddQuotation("SIGN=" + SIGN);
            if (ICONDIR != null && !ICONDIR.Equals("")) arg += " " + AddQuotation("ICONDIR=" + ICONDIR);
            if (OUTDIR != null && !OUTDIR.Equals("")) arg += " " + AddQuotation("OUTDIR=" + OUTDIR);

            Label2.Text = APKTOOL + " -> " + arg;

            System.Diagnostics.Process.Start(APKTOOL, arg);     // 从网站启动的应用程序，需在网站目录下，应用执行时：可读取系统所有目录，写文件仅可写入网站目录

            //Cmd.RunProgram(APKTOOL, arg);
            //String test = "";
        }

        /// <summary>
        /// 为arg添加引号
        /// </summary>
        private static string AddQuotation(string arg)
        {
            if (arg.EndsWith("\\") && !arg.EndsWith("\\\\")) arg += "\\";
            arg = "\"" + arg + "\"";

            return arg;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            String url = "ApkTool.aspx?" + Label3.Text;
            Response.Redirect(url, false);
        }
    }


    public class Cmd
    {
        /// <summary>
        /// 以后台进程的形式执行应用程序（d:\*.exe）
        /// </summary>
        public static Process newProcess(String exe, String Arguments)
        {
            Process P = new Process();
            P.StartInfo.CreateNoWindow = true;
            P.StartInfo.FileName = exe;
            P.StartInfo.UseShellExecute = false;
            P.StartInfo.RedirectStandardError = true;
            P.StartInfo.RedirectStandardInput = true;
            P.StartInfo.RedirectStandardOutput = true;
            P.StartInfo.Arguments = Arguments;
            //P.StartInfo.WorkingDirectory = @"C:\windows\system32";
            P.Start();
            return P;
        }


        /// <summary>
        /// 以进程的形式打开应用程序（d:\*.exe）,并执行命令
        /// </summary>
        public static void RunProgram(String programName, String Arguments)
        {
            Process P = newProcess(programName, Arguments);
            P.WaitForExit(120 * 1000);
            P.Close();
        }



        /// <summary>
        /// 定义委托接口处理函数，用于实时处理cmd输出信息
        /// </summary>
        public delegate void Method();

        /// <summary>
        /// 在新的线程中执行method逻辑
        /// </summary>
        public static void ThreadRun(Method method)
        {
            Thread thread = new Thread(delegate()
            {
                // 执行method逻辑
                if (method != null) method();
            });

            thread.Priority = ThreadPriority.AboveNormal;           // 设置子线程优先级
            Thread.CurrentThread.Priority = ThreadPriority.Highest; // 设置当前线程为最高优先级
            thread.Start();
        }
    }

}